package com.acmedcare.framework.exchange.center.core.resolve;

import com.acmedcare.framework.exchange.center.core.StreamReaderUtil;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@SuppressWarnings("unused")
@Slf4j
public class WGetPathResolve extends HttpPathResolve {

  public WGetPathResolve(String uri, String name, String rootPath) {
    super(uri, name, rootPath);
  }

  public WGetPathResolve(String uri, String rootPath) {

    super(uri, rootPath);
  }


  @Override
  public String resolve() throws Exception {

    Path targetPath = super.getTargetPath();
    final Process ps;
    try {

      ProcessBuilder pb = new ProcessBuilder("wget", super.uri, "-O",
          targetPath.toString());
      ps = pb.start();
    } catch (Exception e) {

      log.error("wget下载http文件失败，正在切换使用http下载文件" + e.getMessage());

      return super.resolve();
    }

    new Thread(() -> StreamReaderUtil.readToFile(ps.getInputStream())).start();
    new Thread(() -> StreamReaderUtil.readToFile(ps.getErrorStream())).start();
    ps.waitFor(30, TimeUnit.MINUTES);
    return targetPath.toString();
  }
}
